package com.chenl.consumer.DEMOS.readTimeOutAop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Timer;
import java.util.TimerTask;

@Aspect
@Component
@Slf4j
public class ReadTimeOutAspect {
    @Around("@annotation(com.chenl.consumer.DEMOS.readTimeOutAop.ReadTimeOut)")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        Thread thread = Thread.currentThread();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ReadTimeOut rateLimit = method.getAnnotation(ReadTimeOut.class);
        long timeout = rateLimit.timeout();
        log.info("readTimeOutAspect---当前接口超时时间为{}秒", new BigDecimal(timeout).divide(new BigDecimal(1000)));
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                thread.interrupt();
            }
        }, timeout);
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Exception e) {
            log.info("readTimeOutAspect---当前接口已超时");
            timer.cancel();
            throw new RuntimeException("Read Time Out ~");
        }
        return proceed;
    }
}
